package com.sinog.front.controller.basic;

import com.sinog.core.model.UserDTO;
import com.sinog.core.util.AesUtil;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.log.Log;
import com.sinog.front.feign.basic.UserService;
import com.sinog.front.service.user.UserFacade;
import com.sinog.front.service.user.UserPwdService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @desc 系统管理 - 用户管理 - 用户管理 - UserController
 * @author -
 * @date -
 */
@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserFacade userFacadeService;
    @Autowired
    private UserPwdService pwdService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 系统管理 - 用户管理 - 用户管理 - 分页查询用户信息
     * @param usernameKey usernameKey
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param pid pid
     * @param id id
     * @param orgid orgid
     * @return String
     */
    @GetMapping("/basic/user/getUserList")
    @ResponseBody
    public String getUserList(HttpServletRequest request,
                              @RequestParam(required = false, defaultValue = "-1") String usernameKey,
                              @RequestParam(required = false, defaultValue = "-1")
                                      Integer pageIndex,Integer pageSize,String pid,String id,String orgid) {
        UserDTO loginUserInfo = userFacadeService.getAuthentication();
        return userService.selectUserList(usernameKey,pageIndex,pageSize,pid,id,orgid,loginUserInfo.getDepartid());
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 保存用户信息（更新/新增）
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "新增", value = "保存用户信息（更新/新增）")
    @PostMapping("/basic/user/save")
    public Result saveUser(HttpServletRequest request,String data) {
        // 插入登陆用户
        Map<String,Object> stringObjectMap = JsonUtil.toMap(data);
        if(StringUtils.isBlank((String)stringObjectMap.get(Constants.StrFinalValue.DEPARTNAME))) {
            pwdService.saveAuthUser(data);
        }
        return userService.save(data);
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 删除用户
     * @param request request
     * @param account account
     * @return Result
     */
    @Log(type = "删除", value = "删除用户")
    @DeleteMapping("/basic/user/{account}")
    public Result delUser(HttpServletRequest request,@PathVariable String account) {
        // 修改登陆用户状态
        String authUser = "{stat:-1,account:\"" + account + "\"}";
        pwdService.saveAuthUser(authUser);
        return userService.deleteOne(account);
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 根据id查询用户
     * @param id id
     * @return Result
     */
    @GetMapping("/basic/user/account/{id}")
    public Result selectUserByAccount(@PathVariable String id) {
        return userService.selectOne(id,"1");
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 个人信息修改
     * @param account account
     * @param phone phone
     * @param email email
     * @param username username
     * @param telphone telphone
     * @return Result
     */
    @PostMapping("/basic/user/user-info-update")
    @ResponseBody
    public Result updateUserInfo(String account,String phone,String email,String username,
                                 @RequestParam(defaultValue = "-1") String telphone) {
        return userService.updateUserInfoOne(account,phone,email,username,telphone);
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 修改密码
     * @param oldpwd oldpwd
     * @param pwd pwd
     * @return Result
     */
    @Log(type = "更新", value = "用户修改密码")
    @PostMapping("/basic/user/user-changepwd")
    public Result selectUserOldPwd(HttpServletRequest request,String oldpwd,String pwd) {
        byte[] decrypted = new byte[0];
        //前端传递密码解密
        String key = "abcdefghijklmn12";
        String iv = "abcdefghijklmn12";
        UserDTO userDTO = userFacadeService.getAuthentication();
        String account = userDTO.getAccount();
        String pwPattern = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*()——+|{}【】‘；：”“’。，、？\\\\\\\\\\w]{8,}$";
        if(StringUtils.isEmpty(pwd)) {
            return Result.failure(ReturnCode.PASSWORD_NOT_NULL);
        }
        try {
            decrypted = AesUtil.aesCbcDecrypt(AesUtil.decryptBase64(pwd),key.getBytes(),iv.getBytes());
        } catch(Exception e) {
            log.error("发生异常:",e);
        }
        String pwd1 = AesUtil.byteToString(decrypted);
        if(!pwd1.matches(pwPattern)) {
            return Result.failure(ReturnCode.PASSWORD_NOT_MZ);
        }
        Result result = pwdService.updatePwd(account,oldpwd,pwd);
        if(Constants.Number.NUM_ONE.equals(result.getCode())) {
            stringRedisTemplate.opsForValue().set("user:password:" + userDTO.getDepartid()
                                                                            .substring(0,2) + ":" + userDTO.getAccount(),"1",180,TimeUnit.DAYS);
        }
        return result;
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 根据账号重置密码
     * @param request Result
     * @param account account
     * @return Result
     */
    @Log(type = "更新", value = "重置用户密码")
    @PostMapping("/basic/user/resetPwd")
    public Result resetPwd(HttpServletRequest request,String account) {
        //判断传入账号是否是当前登录账号的下属机构所属账号
        UserDTO authentication = userFacadeService.getAuthentication();
        //查询入参账号所属部门ID
        Result result = userService.selectOne(account,Constants.NumberStr.NUM_STR_ZERO);
        UserDTO infoByAccount = null;
        if (Constants.Number.NUM_ONE.equals(result.getCode())) {
            String data = (String) result.getData();
            infoByAccount = JsonUtil.toBean(data, UserDTO.class);
        }
        assert infoByAccount != null;
        String childCode = infoByAccount.getDepartid();
        //当前登录账号部门ID
        String parentCode = authentication.getDepartid();
        List<String> departids = userService.selectAllDepartIdByDepartid(parentCode);
        if(!departids.contains(childCode)) {
            return Result.failure(500,"您没有权限重置该账号密码!",null);
        }
        return userService.resetPwd(account);
    }

    /**
     * 系统管理 - 用户管理 - 新增 - 校验手机号是否重复
     * @param phoneNum  手机号码
     * @param account   当前账户
     * @return Result
     */
    @PostMapping("/basic/user/phone")
    public Result checkPhone(@RequestParam(required = false,defaultValue = "-1")String phoneNum,
                             @RequestParam(required = false,defaultValue = "-1")String account) {
        return userService.checkPhone(phoneNum,account);
    }

    /**
     * 山西个性化代码 首页 - 用户信息 - 修改
     * @param userPositionStr account
     * @return Result
     */
    @PostMapping("/basic/user/user-position-update")
    public Result updateUserInfo(String userPositionStr) {
        return userService.updateUserPositionById(userPositionStr);
    }
}